package com.brotherly.framework;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

import com.brotherly.framework.app.BaseApplication;
import com.brotherly.framework.app.BaseApplication.ApplicationReadyListener;
import com.brotherly.framework.event.EventListenerHelper;
import com.brotherly.framework.event.EventService;
import com.brotherly.framework.http.HttpListener;
import com.brotherly.framework.http.HttpService;
import com.brotherly.framework.service.ServiceManager;
import com.brotherly.framework.storage.SimpleStorage;
import com.brotherly.framework.storage.SimpleStorageService;
import com.brotherly.mpgp.ArticleActivity;
import com.brotherly.mpgp.FavoriteActivity;
import com.brotherly.mpgp.MainActivity;
import com.brotherly.mpgp.R;
import com.brotherly.mpgp.remoteinterface.RemoteServerService;
import com.brotherly.mpgp.util.GameManagerUtil;
import com.brotherly.util.BitmapUtil;
import com.brotherly.util.InternetResourceCache;
import com.brotherly.util.downloader.DownLoaderUtil;
import com.umeng.analytics.MobclickAgent;

//import com.brotherly.util.downloader.DownLoaderUtil;

/**
 * 带事件回调的基础Activity
 * 
 * @author EndlessRain
 * 
 */
abstract public class BaseActivity extends Activity implements ApplicationReadyListener, OnCancelListener
{
    public class EventHandler extends EventListenerHelper
    {
        @Override
        public void onEvent(String id, Object param1, Object param2)
        {
            onServiceEvent(id, param1, param2);
        }
    }

    public static final String Activity_Event_Internet_Resource_Download_Success = "Activity_Event_Internet_Resource_Download_Success";
    public static final String Activity_Event_Internet_Resource_Download_Error = "Activity_Event_Internet_Resource_Download_Error";

    private EventHandler mEventHandler = new EventHandler();

    protected int displayHeight;

    protected int displayWidth;

    private ProgressDialog mProgressDialog;

    abstract protected void onServiceEvent(String id, Object param1, Object param2);

    private void attahEvent()
    {
        mEventHandler.setService((EventService) ServiceManager.getInstance().getService(ServiceManager.EVENT_SERVICE));
        mEventHandler.attahEvent(Activity_Event_Internet_Resource_Download_Success);
        mEventHandler.attahEvent(Activity_Event_Internet_Resource_Download_Error);
        mEventHandler.attahEvent(RemoteServerService.RemoteServer_Event_RemoteServer_Success);
        mEventHandler.attahEvent(RemoteServerService.RemoteServer_Event_RemoteServer_Error);

        mEventHandler.attahEvent(DownLoaderUtil.Activity_Event_FileDownload_Info);
        mEventHandler.attahEvent(DownLoaderUtil.Activity_Event_FileDownload_Pause);
        mEventHandler.attahEvent(DownLoaderUtil.Activity_Event_FileDownload_Start);
    }

    private void detachEvent()
    {
        mEventHandler.detachEvent(RemoteServerService.RemoteServer_Event_RemoteServer_Success);
        mEventHandler.detachEvent(RemoteServerService.RemoteServer_Event_RemoteServer_Error);
        mEventHandler.detachEvent(Activity_Event_Internet_Resource_Download_Success);
        mEventHandler.detachEvent(Activity_Event_Internet_Resource_Download_Error);

        mEventHandler.detachEvent(DownLoaderUtil.Activity_Event_FileDownload_Info);
        mEventHandler.detachEvent(DownLoaderUtil.Activity_Event_FileDownload_Pause);
        mEventHandler.detachEvent(DownLoaderUtil.Activity_Event_FileDownload_Start);
        mEventHandler.setService(null);
    }

    abstract public void onAllReady();

    @Override
    public void onApplicationReady()
    {
        BaseApplication.getInstance().unregisterApplicationReadyListener(this);
        attahEvent();
        View back = findViewById(R.id.btn_back);
        if (back != null)
        {
            back.setOnClickListener(new OnClickListener()
            {

                @Override
                public void onClick(View v)
                {
                    finish();
                }
            });
        }
        View favorite = findViewById(R.id.btn_favorite);
        if (favorite != null)
        {
            favorite.setOnClickListener(new OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    boolean isGame = true;
                    if (BaseActivity.this instanceof MainActivity)
                    {
                        MainActivity ma = (MainActivity) BaseActivity.this;
                        if (ma.getCurrentPageIndex() == 1)
                        {
                            isGame = false;
                        }
                    } else if (BaseActivity.this instanceof ArticleActivity)
                    {
                        isGame = false;
                    }
                    Intent intent = new Intent(BaseActivity.this, FavoriteActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
                    intent.putExtra("IsGame", isGame);
                    startActivity(intent);
                }
            });
        }
        onAllReady();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        displayWidth = dm.widthPixels; // 得到宽度
        displayHeight = dm.heightPixels; // 得到高度
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        // mProgressDialog.setIcon(R.drawable.ic_launcher);
        mProgressDialog.setCancelable(true);
        mProgressDialog.setOnCancelListener(this);
    }

    @Override
    protected void onPostResume()
    {
        super.onPostResume();
        BaseApplication.getInstance().setCurrentActivity(this);
    }

    @Override
    protected void onStart()
    {
        super.onStart();
        boolean isallservicesonready = BaseApplication.getInstance().isAllServiceOnReady();
        if (isallservicesonready)
        {
            onApplicationReady();
        } else
        {
            BaseApplication.getInstance().registerApplicationReadyListener(this);
        }
    }

    @Override
    protected void onStop()
    {
        detachEvent();
        if (this == BaseApplication.getInstance().getCurrentActivity())
        {
            BaseApplication.getInstance().setCurrentActivity(null);
        }
        super.onStop();
    }

    public void showProgressDialog(String title)
    {
        if (title != null)
        {
            mProgressDialog.setMessage(title);
        }
        mProgressDialog.show();
    }

    @Override
    protected void onPause()
    {
        MobclickAgent.onPause(this);
        super.onPause();
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void hideProgressDialog()
    {
        mProgressDialog.dismiss();
    }

    protected void onProgressDialogCancel()
    {}

    @Override
    public void onCancel(DialogInterface dialog)
    {
        if (dialog == mProgressDialog)
        {
            onProgressDialogCancel();
        }
    }

    private List<String> mInternetResourceDownloading = new ArrayList<String>();

    public void removeCachedData(final String url)
    {
        InternetResourceCache.getInstance().removeCachedData(url);
    }

    private LinkedList<String> mBadUrls = new LinkedList<String>();

    public boolean imageViewLoadInternetResource(ImageView imageview, String url, int defaultRes)
    {
        ColorDrawable defaultColor = null;
        if (defaultRes == 0)
        {
            defaultColor = new ColorDrawable(0x00000000);
        }
        if (mBadUrls.contains(url))
        {
            if (defaultColor == null)
            {
                imageview.setImageResource(defaultRes);
            } else
            {
                imageview.setImageDrawable(defaultColor);
            }
            return false;
        }
        String localPath = internetResourceDownload(url);
        if (localPath == null)
        {
            imageview.setImageResource(defaultRes);
        } else
        {
            Bitmap bp = BitmapUtil.loadBitmap(localPath);
            if (bp != null)
            {
                imageview.setImageBitmap(bp);
                return true;
            } else
            {
                if (!mBadUrls.contains(url))
                {
                    mBadUrls.add(url);
                }
                if (defaultColor == null)
                {
                    imageview.setImageResource(defaultRes);
                } else
                {
                    imageview.setImageDrawable(defaultColor);
                }
            }
        }
        return false;
    }

    public String internetResourceDownload(final String url)
    {
        final EventService eventService = (EventService) ServiceManager.getInstance().getService(ServiceManager.EVENT_SERVICE);
        HttpService httpService = (HttpService) ServiceManager.getInstance().getService(ServiceManager.HTTP_SERVICE);
        String cachePath = InternetResourceCache.getInstance().getCacheFilename(url);
        if (cachePath != null)
        {
            return cachePath;
        } else
        {
            synchronized (mInternetResourceDownloading)
            {
                if (mInternetResourceDownloading.indexOf(url) != -1)
                {
                    return null;
                }
                mInternetResourceDownloading.add(url);
            }
            InternetResourceCache.getInstance().cacheHttpResource(url, "GET", null, null, new HttpListener()
            {

                @Override
                public void result(int code, Map<String, String> headers, byte[] body)
                {
                    String cachePath = InternetResourceCache.getInstance().getCacheFilename(url);
                    synchronized (mInternetResourceDownloading)
                    {
                        mInternetResourceDownloading.remove(url);
                    }
                    if (cachePath != null)
                    {
                        eventService.signEvent(Activity_Event_Internet_Resource_Download_Success, url, cachePath);
                    } else
                    {
                        if (!mBadUrls.contains(url))
                        {
                            mBadUrls.add(url);
                        }
                        eventService.signEvent(Activity_Event_Internet_Resource_Download_Error, url, cachePath);
                    }
                }
            }, false, httpService);
            return null;
        }
    }

    public void shareArticle(String title, int articleref)
    {
        // 分享
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain"); // 纯文本
        /*
         * 图片分享 it.setType("image/png"); //添加图片 File f = new
         * File(Environment.getExternalStorageDirectory() +"/Pictures/2.png");
         * Uri u = Uri.fromFile(f); it.putExtra(Intent.EXTRA_STREAM, u);
         */
        intent.putExtra(Intent.EXTRA_SUBJECT, "手游秘籍分享");
        if (title != null)
        {
            intent.putExtra(Intent.EXTRA_TEXT, "今天我在手游秘籍上看到了一篇好攻略《" + title
                    + "》，大家赶快去看看啊。http://www.play.cn/r/cms/www/web/v01/common/other/symj.apk");
        } else
        {
            intent.putExtra(Intent.EXTRA_TEXT, "今天我在手游秘籍上看到了一篇好攻略，大家赶快去看看啊。www.play.cn/r/cms/www/web/v01/common/other/symj.apk");

        }
        startActivity(Intent.createChooser(intent, "手游秘籍-秘籍分享"));
    }

    public void shareGame(String name, int gameref)
    {
        // 分享
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain"); // 纯文本
        /*
         * 图片分享 it.setType("image/png"); //添加图片 File f = new
         * File(Environment.getExternalStorageDirectory() +"/Pictures/2.png");
         * Uri u = Uri.fromFile(f); it.putExtra(Intent.EXTRA_STREAM, u);
         */
        intent.putExtra(Intent.EXTRA_SUBJECT, "手机网游分享");
        intent.putExtra(Intent.EXTRA_TEXT, "今天我在手游秘籍上发现了一个很好玩的游戏:" + name
                + " ，大家赶快去下啊。http://www.play.cn/r/cms/www/web/v01/common/other/symj.apk");
        startActivity(Intent.createChooser(intent, "手游秘籍-游戏分享"));
    }

    public boolean isFavoriteGame(int gameref)
    {
        SimpleStorageService sss = (SimpleStorageService) ServiceManager.getInstance().getService(
                ServiceManager.SIMPLESTORAGE_SERVICE);
        SimpleStorage ss = sss.openStorage("gamefavorite");
        String ids = ss.get("gamefavoriteid");
        ss.close();
        String[] idarray = null;
        if (ids != null)
        {
            idarray = ids.split("-");
        }
        int[] result = new int[idarray != null ? idarray.length : 0];
        for (int i = 0; i < result.length; i++)
        {
            result[i] = Integer.parseInt(idarray[i]);
        }
        for (int id : result)
        {
            if (id == gameref)
            {
                return true;
            }
        }
        return false;
    }

    public boolean isFavoriteArticle(int articleref)
    {
        SimpleStorageService sss = (SimpleStorageService) ServiceManager.getInstance().getService(
                ServiceManager.SIMPLESTORAGE_SERVICE);
        SimpleStorage ss = sss.openStorage("articlefavorite");
        String ids = ss.get("articlefavoriteid");
        ss.close();
        String[] idarray = null;
        if (ids != null)
        {
            idarray = ids.split("-");
        }
        int[] result = new int[idarray != null ? idarray.length : 0];
        for (int i = 0; i < result.length; i++)
        {
            result[i] = Integer.parseInt(idarray[i]);
        }
        for (int id : result)
        {
            if (id == articleref)
            {
                return true;
            }
        }
        return false;
    }

    public int[] getFavoriteGameIds()
    {
        SimpleStorageService sss = (SimpleStorageService) ServiceManager.getInstance().getService(
                ServiceManager.SIMPLESTORAGE_SERVICE);
        SimpleStorage ss = sss.openStorage("gamefavorite");
        String ids = ss.get("gamefavoriteid");
        String[] idarray = null;
        if (ids != null)
        {
            idarray = ids.split("-");
        }
        LinkedList<Integer> idlist = new LinkedList<Integer>();
        for (int i = 0; idarray != null && i < idarray.length; i++)
        {
            int id = Integer.parseInt(idarray[i]);
            if (!GameManagerUtil.isInstalledGame(id))
            {
                idlist.add(id);
            }
        }
        ss.close();
        int[] result = new int[idlist.size()];
        for (int i = 0; i < idlist.size(); i++)
        {
            result[i] = idlist.get(i);
        }
        return result;
    }

    public int[] getFavoriteArticleIds()
    {
        SimpleStorageService sss = (SimpleStorageService) ServiceManager.getInstance().getService(
                ServiceManager.SIMPLESTORAGE_SERVICE);
        SimpleStorage ss = sss.openStorage("articlefavorite");
        String ids = ss.get("articlefavoriteid");

        String[] idarray = null;
        if (ids != null)
        {
            idarray = ids.split("-");
        }
        int[] result = new int[idarray != null ? idarray.length : 0];
        for (int i = 0; i < result.length; i++)
        {
            result[i] = Integer.parseInt(idarray[i]);
        }
        ss.close();
        return result;
    }

    public JSONObject getFavoriteGame(int gameref)
    {
        SimpleStorageService sss = (SimpleStorageService) ServiceManager.getInstance().getService(
                ServiceManager.SIMPLESTORAGE_SERVICE);
        SimpleStorage ss = sss.openStorage("gamefavorite");
        String gamejson = ss.get("gamefavorite" + gameref);
        ss.close();
        JSONObject result = null;
        try
        {
            result = new JSONObject(gamejson);
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
        return result;
    }

    public JSONObject getFavoriteArticle(int articleref)
    {
        SimpleStorageService sss = (SimpleStorageService) ServiceManager.getInstance().getService(
                ServiceManager.SIMPLESTORAGE_SERVICE);
        SimpleStorage ss = sss.openStorage("articlefavorite");
        String gamejson = ss.get("articlefavorite" + articleref);
        ss.close();
        JSONObject result = null;
        try
        {
            result = new JSONObject(gamejson);
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
        return result;
    }

    public void favoriteGame(int gameref, JSONObject gamejson)
    {
        int[] ids = getFavoriteGameIds();
        for (int id : ids)
        {
            if (id == gameref)
            {
                return;
            }
        }
        SimpleStorageService sss = (SimpleStorageService) ServiceManager.getInstance().getService(
                ServiceManager.SIMPLESTORAGE_SERVICE);
        SimpleStorage ss = sss.openStorage("gamefavorite");
        StringBuffer sb = new StringBuffer();
        for (int id : ids)
        {
            sb.append(id + "-");
        }
        sb.append(gameref + "");
        ss.begin();
        ss.put("gamefavoriteid", sb.toString());
        ss.put("gamefavorite" + gameref, gamejson.toString());
        ss.commit();
        ss.close();
    }

    public void delFavoriteGame(int gameref)
    {
        int[] ids = getFavoriteGameIds();
        SimpleStorageService sss = (SimpleStorageService) ServiceManager.getInstance().getService(
                ServiceManager.SIMPLESTORAGE_SERVICE);
        SimpleStorage ss = sss.openStorage("gamefavorite");
        StringBuffer sb = new StringBuffer();
        for (int id : ids)
        {
            if (id != gameref)
            {
                sb.append(id + "-");
            }
        }
        ss.begin();
        if (sb.toString().trim().equals(""))
        {
            ss.remove("gamefavoriteid");
        } else
        {
            ss.put("gamefavoriteid", sb.toString());
        }
        ss.remove("gamefavorite" + gameref);
        ss.commit();
        ss.close();
    }

    public void favoriteArticle(int articleref, JSONObject articlejson)
    {
        int[] ids = getFavoriteArticleIds();
        for (int id : ids)
        {
            if (id == articleref)
            {
                return;
            }
        }
        StringBuffer sb = new StringBuffer();
        for (int id : ids)
        {
            sb.append(id + "-");
        }
        sb.append(articleref + "");
        SimpleStorageService sss = (SimpleStorageService) ServiceManager.getInstance().getService(
                ServiceManager.SIMPLESTORAGE_SERVICE);
        SimpleStorage ss = sss.openStorage("articlefavorite");
        ss.begin();
        ss.put("articlefavoriteid", sb.toString());
        ss.put("articlefavorite" + articleref, articlejson.toString());
        ss.commit();
        ss.close();
    }

    public void delFavoriteArticle(int articleref)
    {
        int[] ids = getFavoriteArticleIds();
        SimpleStorageService sss = (SimpleStorageService) ServiceManager.getInstance().getService(
                ServiceManager.SIMPLESTORAGE_SERVICE);
        SimpleStorage ss = sss.openStorage("articlefavorite");
        StringBuffer sb = new StringBuffer();
        for (int id : ids)
        {
            if (id != articleref)
            {
                sb.append(id + "-");
            }
        }
        ss.begin();
        if (sb.toString().trim().equals(""))
        {
            ss.remove("articlefavoriteid");
        } else
        {
            ss.put("articlefavoriteid", sb.toString());
        }
        ss.remove("articlefavorite" + articleref);
        ss.commit();
        ss.close();
    }

}
